﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;

namespace PacoToolKit.File
{
    public class Common
    {
        /// <summary>
        /// 读取文件到byte[]
        /// </summary>
        /// <param name="filePath"></param>
        /// <returns></returns>
        public static byte[] ReadFile(string filePath)
        {
            using (FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read))
            {
                byte[] bytes = new byte[(int)fs.Length];
                fs.Read(bytes, 0, bytes.Length);
                fs.Close();
                return bytes;
            }
        }

        /// <summary>
        /// 读取文件到string
        /// </summary>
        /// <param name="filePath"></param>
        /// <returns></returns>
        public static string ReadFileToString(string filePath)
        {
            string ret = string.Empty;
            using (FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read))
            {
                StreamReader sr = new StreamReader(fs, Encoding.Default);
                ret = sr.ReadToEnd();
            }
            return ret;
        }

        /// <summary>
        /// 获取文件夹下所有文件信息
        /// </summary>
        /// <param name="folderPath"></param>
        /// <returns>所有文件信息</returns>
        public static FileInfo[] GetFolderFileInfos(string folderPath)
        {
            var files = new DirectoryInfo(folderPath).GetFiles();
            return files;
        }

        /// <summary>
        /// 获取文件夹下所有文件名
        /// </summary>
        /// <param name="folderPath"></param>
        /// <param name="pattern">匹配文件类型，支持通配符，类似 "*.html"</param>
        /// <returns></returns>
        public static string[] GetFiles(string folderPath,string pattern)
        {
            if(string.IsNullOrEmpty(pattern))
            {
                pattern = "*.*";
            }
            var fileNames = Directory.GetFiles(folderPath, pattern);
            return fileNames;
        }

        /// <summary>
        /// 删除文件
        /// </summary>
        /// <param name="fileName"></param>
        public static void DeleteFile(string fileName)
        {
            if(System.IO.File.Exists(fileName))
            {
                // Use a try block to catch IOExceptions, to
                // handle the case of the file already being
                // opened by another process.
                try
                {
                    System.IO.File.Delete(fileName);
                }
                catch (System.IO.IOException e)
                {
                    throw e;
                }
            }
        }
    }
}
